package com.minimoment.util.common;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * Created by etund on 2014/10/21.
 */
@SuppressWarnings("all")
public class CommomUtils {
    /**
     * Base64加密
     * 只需要传入一个字符串
     * 思路：
     * a 新建字节数组和字符串
     * b 得到传进来的字符串的字节数组，并设置编码为utf-8
     * c 调用java自带的BASE64ENCODE().encode(byte[])方法得到对应的加密或的字符串
     * d 返回
     * @param str
     * @return
     */
    public static String mBase64Encode(String str) {
        try {
            byte[] b = null;
            String s = null;
            b = str.getBytes("utf-8");
            if (b != null) {
                s = new BASE64Encoder().encode(b);
            }
            return s;
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 利用java自带的Base64Decode解密只需要已经加密好的Base64编码即可
     * 思路
     * a 新建字节数组和字符串
     * b 调用BASE64Decoder的decodeBuffer(String )方法a
     * c s = new String(),添加字节数组，并设置编码方式，返回一个字符串
     * c 返回s
     *
     * @param str
     * @return
     */
    public static String mBase64Decode(String str) {
        byte[] b = null;
        String s = null;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            b = decoder.decodeBuffer(str);
            s = new String(b, "utf-8");
            return s;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     *   * 添加Cookie
     *   传入的是由你想要存的信息用_组成的长字符串，和你想要存的信息的名字
     * @param info:想要存的信息串
     * @param infoName:要存的信息名字
     * @param response
     */
    public static void addCookie(String info , String infoName, HttpServletResponse response) {
        System.out.println(info+"===="+infoName);
        System.out.println(info+"======str=======");
        Cookie c = new Cookie(infoName,info );
        c.setMaxAge(7 * 24 * 60 * 60);
        response.addCookie(c);
    }


    /**
     * 得到cookie
     * 传入的是你要得到的cookie名字，和请求，得到的是你需要的信息的字符串数组
     * @param request:
     * @param :得到的是你需要的信息的字符串数组
     * @return
     */
    public static String[] getCookie(HttpServletRequest request, String infoName) {
        System.out.println(infoName+"=====str=====");
        Cookie[] cookies = request.getCookies();
        System.out.println(cookies+"===========================");
        String unDoString;
        String[] infos = null;
        System.out.println(infoName+"=======str======");
        /**
         * 当服务器启动的时候：第一次请求cookies为空
         *                                 第二次请求，cookie还是为空
         *                                 第三次请求，cookie不为空，但是找不到对应的cookie值
         *                                 三次请求str都有值
         */
        if(cookies!=null){
            for(Cookie cookie:cookies){
                System.out.println(infoName+"=======str======");
                System.out.println(cookie.getName()+"========cookie.getName=======");
                if(infoName.equals(cookie.getName())){
                    unDoString = cookie.getValue();
                    System.out.println(unDoString);
                    infos = unDoString.split("_");
                    for(int i = 0 ; i<infos.length;i++){
                        System.out.println(infos[i]);
                    }
                }
            }
        }
        return infos;
    }

    /**
     * 删除指定cookie
     * @param str
     */
    public static void delCookie(HttpServletResponse response,String str){
        Cookie cookie = new Cookie(str,null);
        cookie.setMaxAge(-1);
        response.addCookie(cookie);
    }

    /**
     * 获取本机的真实IP地址
     * @return
     * @throws Exception
     */
    public static String getRealIp() {
        try {
            String localip = null;// 本地IP，如果没有配置外网IP则返回它
            String netip = null;// 外网IP

            Enumeration<NetworkInterface> netInterfaces =
                    NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            boolean finded = false;// 是否找到外网IP
            while (netInterfaces.hasMoreElements() && !finded) {
                NetworkInterface ni = netInterfaces.nextElement();
                Enumeration<InetAddress> address = ni.getInetAddresses();
                while (address.hasMoreElements()) {
                    ip = address.nextElement();
                    if (!ip.isSiteLocalAddress()
                            && !ip.isLoopbackAddress()
                            && ip.getHostAddress().indexOf(":") == -1) {// 外网IP
                        netip = ip.getHostAddress();
                        finded = true;
                        break;
                    } else if (ip.isSiteLocalAddress()
                            && !ip.isLoopbackAddress()
                            && ip.getHostAddress().indexOf(":") == -1) {// 内网IP
                        localip = ip.getHostAddress();
                    }
                }
            }

            if (netip != null && !"".equals(netip)) {
                return netip;
            } else {
                return localip;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
